package hy.buy;

import hy.Util;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.concurrent.CountDownLatch;

public class SuperSell {
    public static void main(String[] args)throws Exception {
        final JedisPool pool = Util.getInstance();
        Jedis j = pool.getResource();
        j.set("count","10");
        //先产生队列并清空
        j.ltrim("orders",-1,0);
        CountDownLatch cl = new CountDownLatch(1000);
        for (int i = 0; i < 1000; i++) {
            new Thread(i+"号客户"){
                @Override
                public void run() {
                    try(Jedis j = pool.getResource()){
                        long count = Long.parseLong(j.get("count"));
                        if(count<=0){
                            System.out.println("没有商品，退出");
                            return;
                        }

                        count = j.decr("count");
                        if(count>=0){
                            j.rpush("orders", Thread.currentThread().getName());
                        }else {
                            System.out.println("虽然你成功完成了减库存，但你还是不能买");
                        }
                    }finally {
                        cl.countDown();
                    }
                }
            }.start();
        }
        cl.await();
        System.out.println(j.lrange("orders", 0, -1));
        j.close();
    }
}
